package com.ruoyi.inspection.service.impl;

import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.inspection.domain.GovernCheckTaskPlan;
import com.ruoyi.inspection.domain.GovernCheckTaskPlanItem;
import com.ruoyi.inspection.domain.vo.GovernCheckTaskPlanVo;
import com.ruoyi.inspection.mapper.GovernCheckTaskPlanItemMapper;
import com.ruoyi.inspection.mapper.GovernCheckTaskPlanMapper;
import com.ruoyi.inspection.service.GovernCheckTaskPlanService;
import com.ruoyi.inspection.utils.BeanUtils;
import com.ruoyi.inspection.utils.IdFactory;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 政府专项检查计划表(GovernCheckTaskPlan)表服务实现类
 *
 * @author makejava
 * @since 2024-06-19 16:16:10
 */
@Service("governCheckTaskPlanService")
public class GovernCheckTaskPlanServiceImpl implements GovernCheckTaskPlanService {
    @Resource
    private GovernCheckTaskPlanItemMapper governCheckTaskPlanItemMapper;
    @Resource
    private GovernCheckTaskPlanMapper governCheckTaskPlanMapper;
    @Resource
    private ISysUserService sysUserService;
    @Autowired
    private SysUserMapper userMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param governTaskPlanId 主键
     * @return 实例对象
     */
    @Override
    public GovernCheckTaskPlan queryById(Long governTaskPlanId) {
        GovernCheckTaskPlan taskPlan = this.governCheckTaskPlanMapper.queryById(governTaskPlanId);
        if (StringUtils.isNotNull(taskPlan)) {
            taskPlan.setGovernCheckTaskPlanItemList(new ArrayList<>());
        }
        return taskPlan;
    }

    /**
     * 分页查询
     *
     * @param governCheckTaskPlan 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskPlan> queryByPage(GovernCheckTaskPlan governCheckTaskPlan) {
        List<GovernCheckTaskPlan> governCheckTaskPlans = this.governCheckTaskPlanMapper.queryTaskPlanList(governCheckTaskPlan);
        if (StringUtils.isEmpty(governCheckTaskPlans)) {
            return new ArrayList<GovernCheckTaskPlan>();
        }

        handleTaskPlan(governCheckTaskPlans, null);

        return governCheckTaskPlans;
    }

    public void handleTaskPlan(List<GovernCheckTaskPlan> governCheckTaskPlans, String checkUserId) {
        GovernCheckTaskPlanItem taskPlanItem = new GovernCheckTaskPlanItem();
        List<GovernCheckTaskPlanItem> planItems = null;


        for (GovernCheckTaskPlan checkTaskPlan : governCheckTaskPlans) {
            taskPlanItem.setGovernCheckUserId(checkUserId);
            taskPlanItem.setGovernTaskPlanId(checkTaskPlan.getGovernTaskPlanId());
            planItems = governCheckTaskPlanItemMapper.queryAllByLimit(taskPlanItem);
            long un = 0, co = 0;
            if (StringUtils.isNotEmpty(planItems)) {
                un = planItems.stream().map(GovernCheckTaskPlanItem::getGovernCheckResult).filter("未排查"::equals).count();
                co = planItems.size() - un;
            }
            checkTaskPlan.setUnCompleteCount(un);
            checkTaskPlan.setCompleteCount(co);
        }
    }

    /**
     * 分页查询
     *
     * @param governCheckTaskPlan 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskPlan> queryList(GovernCheckTaskPlan governCheckTaskPlan) {
        List<GovernCheckTaskPlan> governCheckTaskPlans = this.governCheckTaskPlanMapper.queryAllByLimit(governCheckTaskPlan);
        for (GovernCheckTaskPlan checkTaskPlan : governCheckTaskPlans) {
            List<GovernCheckTaskPlanItem> governCheckTaskPlanItemList = checkTaskPlan.getGovernCheckTaskPlanItemList();
            long un = governCheckTaskPlanItemList.stream().map(GovernCheckTaskPlanItem::getGovernCheckResult).filter("未排查"::equals).count();
            long co = governCheckTaskPlanItemList.size() - un;
            checkTaskPlan.setUnCompleteCount(un);
            checkTaskPlan.setCompleteCount(co);
            checkTaskPlan.setGovernCheckTaskPlanItemList(new ArrayList<>());
        }
        return governCheckTaskPlans;
    }

    /**
     * 查询
     *
     * @param governCheckTaskPlan 筛选条件
     * @return 查询结果
     */
    @Override
    public GovernCheckTaskPlan selectGovernCheckTaskPlan(GovernCheckTaskPlan governCheckTaskPlan) {
        List<GovernCheckTaskPlan> list = this.queryList(governCheckTaskPlan);

        return StringUtils.isEmpty(list) ? null : list.get(0);
    }

    /**
     * 查询我的检查任务
     *
     * @param governCheckTaskPlan 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskPlan> selectByCheckUser(GovernCheckTaskPlan governCheckTaskPlan) {
        List<GovernCheckTaskPlan> governCheckTaskPlans = this.governCheckTaskPlanMapper.queryUserTaskPlanList(governCheckTaskPlan);

        handleTaskPlan(governCheckTaskPlans, governCheckTaskPlan.getCheckUserId());
        return governCheckTaskPlans;
    }


    /**
     * 查询我的检查任务(APP)
     *
     * @param governCheckTaskPlan 筛选条件
     * @return 查询结果
     */
    @Override
    public List<GovernCheckTaskPlanVo> selectUsersTaskList(GovernCheckTaskPlan governCheckTaskPlan) {
        List<GovernCheckTaskPlan> governCheckTaskPlans = this.governCheckTaskPlanMapper.queryUserTaskPlanList(governCheckTaskPlan);
        if (StringUtils.isEmpty(governCheckTaskPlans)) {
            return new ArrayList<GovernCheckTaskPlanVo>();
        }

        return handleUserTaskPlan(governCheckTaskPlans, governCheckTaskPlan.getCheckUserId());
    }

    public List<GovernCheckTaskPlanVo> handleUserTaskPlan(List<GovernCheckTaskPlan> governCheckTaskPlans, String checkUserId) {
        List<GovernCheckTaskPlanVo> taskPlanList = new ArrayList<GovernCheckTaskPlanVo>();
        GovernCheckTaskPlanVo governCheckTaskPlanVo = null;

        GovernCheckTaskPlanItem taskPlanItem = new GovernCheckTaskPlanItem();
        List<GovernCheckTaskPlanItem> planItems = null;

        for (GovernCheckTaskPlan checkTaskPlan : governCheckTaskPlans) {
            governCheckTaskPlanVo = new GovernCheckTaskPlanVo();
            BeanUtils.copyBeanProp(governCheckTaskPlanVo, checkTaskPlan);

            taskPlanItem.setGovernCheckUserId(checkUserId);
            taskPlanItem.setGovernTaskPlanId(checkTaskPlan.getGovernTaskPlanId());
            planItems = governCheckTaskPlanItemMapper.queryAllByLimit(taskPlanItem);

            long un = planItems.stream().map(GovernCheckTaskPlanItem::getGovernCheckResult).filter("未排查"::equals).count();
            long total = planItems.size();
            governCheckTaskPlanVo.setCompleteCount(total - un);
            governCheckTaskPlanVo.setUnCompleteCount(un);

            Date endDate = checkTaskPlan.getGovernTaskEndTime();
            boolean isTimeOut = (endDate!=null && endDate.getTime() < System.currentTimeMillis()) ? true : false;
            String taskResult = un==0 ? "已排查" : isTimeOut ? "已超时"
                    : un==total ? "待排查" : "进行中";
            governCheckTaskPlanVo.setGovernCheckResult(taskResult);
            taskPlanList.add(governCheckTaskPlanVo);
        }

        return taskPlanList;
    }

    /**
     * 新增数据
     *
     * @param governCheckTaskPlan 实例对象
     * @return 实例对象
     */
    @Override
    public GovernCheckTaskPlan insert(GovernCheckTaskPlan governCheckTaskPlan) {
        if (StringUtils.isEmpty(governCheckTaskPlan.getGovernCheckCompany())) {
            governCheckTaskPlan.setGovernCheckCompany(GlobalConstants.COMPANY_CODE);
        }
        if (StringUtils.isEmpty(governCheckTaskPlan.getGovernCheckSource())) {
            governCheckTaskPlan.setGovernCheckSource(InspectionConstant.JIAN_CHA_LAI_YUAN);
        }
        if (StringUtils.isEmpty(governCheckTaskPlan.getGovernCheckLevel())) {
            governCheckTaskPlan.setGovernCheckLevel(InspectionConstant.JIAN_CHA_JI_BIE);
        }
        if (governCheckTaskPlan.getGovernPlanStatus()==1) {
            governCheckTaskPlan.setGovernTaskRegisterTime(new Date());
        }
        governCheckTaskPlan.setGovernTaskPlanId(IdFactory.newLongId());
        governCheckTaskPlan.setGovernCreateDate(new Date());

        this.governCheckTaskPlanMapper.insert(governCheckTaskPlan);
        return governCheckTaskPlan;
    }

    /**
     * 修改数据
     *
     * @param governCheckTaskPlan 实例对象
     * @return 实例对象
     */
    @Override
    public boolean updateTaskInfo(GovernCheckTaskPlan governCheckTaskPlan) {
        // 更新计划完成状态
        if (governCheckTaskPlan.getGovernCheckVerify()==1) {
            return updatePlanCompleteStatus(governCheckTaskPlan);
        }
        // 更新计划发布状态
        return updatePlanPublishStatus(governCheckTaskPlan);
    }

    /**
     * 确认提交发布检查计划
     * @param governCheckTaskPlan
     * @return
     */
    public boolean updatePlanPublishStatus(GovernCheckTaskPlan governCheckTaskPlan) {
        Date registerTime = governCheckTaskPlan.getGovernTaskRegisterTime();
        // 任务发布状态 0暂存 1已发布
        Integer governPlanStatus = governCheckTaskPlan.getGovernPlanStatus();

        // 判断任务是否已发布
        if (governPlanStatus!=null && governPlanStatus==1 && registerTime==null) {
            governCheckTaskPlan.setGovernTaskRegisterTime(new Date());
        }
        governCheckTaskPlan.setGovernUpdateDate(new Date());
        this.update(governCheckTaskPlan);

        return addUserRole(governCheckTaskPlan.getGovernCheckUserIds());
    }

    /**
     * 人员添加角色
     * @param userIds
     * @return
     */
    public boolean addUserRole(String userIds) {
        if (StringUtils.isEmpty(userIds)) {
            return false;
        }

        for (String userId : userIds.split(",")) {
            if (StringUtils.isEmpty(userId)) {
                continue;
            }
            SysUserRole userRole = sysUserService.selectByUserIdAndRoleId(Long.parseLong(userId), InspectionConstant.ROLE_ZXPC_ID);
            if (userRole==null) {
                sysUserService.insertUserAuth(Long.parseLong(userId), new Long[]{InspectionConstant.ROLE_ZXPC_ID});
            }
        }

        return true;
    }

    /**
     * 确认已完成检查计划
     *
     * @param governCheckTaskPlan
     * @return
     */
    public boolean updatePlanCompleteStatus(GovernCheckTaskPlan governCheckTaskPlan) {
        Long governTaskPlanId = governCheckTaskPlan.getGovernTaskPlanId();
        if (!isFinishPlan(governTaskPlanId)) {
            throw new ServiceException("有未完成的任务项，操作无法执行！");
        }

        governCheckTaskPlan.setGovernUpdateDate(new Date());
        governCheckTaskPlan.setGovernTaskCompleteTime(new Date());
        this.update(governCheckTaskPlan);
        return true;
    }

    /**
     * 修改数据
     *
     * @param governCheckTaskPlan 实例对象
     * @return 实例对象
     */
    @Override
    public int update(GovernCheckTaskPlan governCheckTaskPlan) {
        return this.governCheckTaskPlanMapper.update(governCheckTaskPlan);
    }

    /**
     * 确认检查计划下的任务项是否全部完成
     * @param governTaskPlanId
     * @return
     */
    public boolean isFinishPlan(Long governTaskPlanId) {
        GovernCheckTaskPlanItem searchVo = new GovernCheckTaskPlanItem();
        searchVo.setGovernTaskPlanId(governTaskPlanId);
        searchVo.setGovernCheckResult("未排查");
        searchVo.setHasCheckUser("1");
        searchVo.setGovernDeleted(0);
        List<GovernCheckTaskPlanItem> list = governCheckTaskPlanItemMapper.queryAllByLimit(searchVo);

        return StringUtils.isEmpty(list);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.governCheckTaskPlanMapper.deleteById(id) > 0;
    }

    /**
     * 通过ID查询检查人员
     *
     * @param governTaskPlanId 主键
     * @return 实例对象
     */
    @Override
    public List<SysUser> queryCheckUsers(Long governTaskPlanId) {
        GovernCheckTaskPlan taskPlan = this.governCheckTaskPlanMapper.queryById(governTaskPlanId);
        String checkUserIds = taskPlan.getGovernCheckUserIds();

        List<SysUser> checkUserList = new ArrayList<SysUser>();
        if (StringUtils.isEmpty(checkUserIds)) {
            return checkUserList;
        }

        return Arrays.stream(checkUserIds.split(","))
                .map(id -> {
                    SysUser user = userMapper.selectUserById(Long.parseLong(id));
                    user.setDept(null);
                    user.setRoles(null);
                    return user;
                }).collect(Collectors.toList());
    }
}
